package org.wmq.organizationmanagement.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.wmq.organizationmanagement.common.Result;
import org.wmq.organizationmanagement.model.dto.MemberDTO;
import org.wmq.organizationmanagement.model.po.Member;
import org.wmq.organizationmanagement.model.vo.MemberVO;
import org.wmq.organizationmanagement.service.MemberService;

import java.util.List;

@RestController
@RequestMapping("member")
@RequiredArgsConstructor
@Slf4j
public class MemberController {
    private final MemberService memberService;
    @GetMapping("/{name}")
    public Result<List<MemberVO>> getMemberByName(@PathVariable String name){
        List<MemberVO> resultList = this.memberService.getMemberByName(name);
        if (resultList == null || resultList.isEmpty()){
            log.error("查询会员失败，用户名不存在");
            return Result.error("查询会员失败，用户名不存在");
        }
        log.info("查询会员成功，结果为：{}", resultList);
        return Result.ok(resultList);
    }
    @PostMapping
    public Result<Void> addMember(@RequestBody MemberDTO memberDTO){
        Member member = new Member();
        BeanUtils.copyProperties(memberDTO,member);
        boolean saveSuccess = this.memberService.save(member);
        if (!saveSuccess){
            log.error("添加会员失败");
            return Result.error("添加会员失败");
        }
        log.info("添加会员成功");
        return Result.ok();
    }
    @DeleteMapping("/{id}")
    public Result<Void> deleteMember(@PathVariable Long id){
        this.memberService.removeMemberById(id);
        return Result.ok();
    }
    @PutMapping
    public Result<Void> updateMember(@RequestBody MemberVO memberVO){
        Member member = new Member();
        BeanUtils.copyProperties(memberVO,member);
        boolean updateSuccess = this.memberService.updateById(member);
        if (!updateSuccess){
            log.error("更新会员失败");
        }
        log.info("更新会员成功");
        return Result.ok();
    }


}
